import React,{useState,useEffect} from 'react'
import { Table, Tag, Space,Button } from 'antd';
import { tradeData,tradeDelete } from '../../api/trade';
import {connect} from 'react-redux'
function TradeList(props) {
    let [trade,setTrade] = useState([]);
    let {rules} = props.user.userInfo;
    const columns = [
        {
          title: '数据库Id',
          dataIndex: 'objectId',
          key: 'objectId',
          render: text => <span>{text}</span>,
        },
        {
          title: '行业名称',
          dataIndex: 'tradename',
          key: 'tradename',
        },
        {
            title: '展示图片',
            dataIndex: 'imageUrl',
            key: 'imageUrl',
            render: imageUrl => {
                return (
                 <img src={imageUrl} alt='' style={{width:'50px'}}/>
                )
            }
        },
        {
          title: '是否热推',
          dataIndex: 'hot',
          key: 'hot',
          render: hot => {
              let color = hot === "1" ? 'red' : 'geekblue';
              let word = hot === "1" ? '是' : "否";
              return (
                <Tag color={color}>
                    {word}
                </Tag>
              )
          }
        },
        {
          title: 'Action',
          key: 'action',
          render: (text, record) => (
            <Space size="middle">
                <Button type='primary' onClick={()=>{handleEdit(record)}}>编辑</Button>
            {
                rules === 'root' 
                ? <Button type='primary' danger onClick={()=>{handleDelete(record)}}>删除</Button>
                : ''
            }
            </Space>
          ),
        },
      ];
    useEffect(()=>{
        tradeData().then(res=>{
            setTrade(res.data.results)
        })
    },[])
    let handleEdit = (rowData)=>{
        console.log(rowData)
        props.history.push({
            pathname:'/main/tradetrans/tradeedit',
            search:encodeURIComponent(JSON.stringify(rowData))
        })
    }
    let handleDelete = (rowData)=>{
        tradeDelete(rowData.objectId).then(res=>{
            let len = trade.length;
            for(let i = 0; i < len; i++){
                if(rowData.objectId === trade[i].objectId){
                    trade.splice(i,1)
                    break;
                }
            }
            setTrade([...trade])
        })
    }
   
    return (
        <div>
            <Table 
                columns={columns} 
                dataSource={trade} 
                rowKey='objectId'
            />
        </div>
    )
}
export default connect(state=>state)(TradeList)